package ribbon;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

/**
 * 作用：采用nacos来实现基于权重的负载均衡算法
 * 测试：nacos控制台将其中一个实例的权重设置为0，查看调用情况
 */
public class MyRibbonRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        Instance instance = null;

        try {
            // 获取Ribbon相关API
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();

            // 获取需要调用的服务名
            String serviceName = loadBalancer.getName();

            // 获取服务发现相关API
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

            // 利用nacos的基于权重的负载均衡算法，选出一个实例
            instance = namingService.selectOneHealthyInstance(serviceName);
        } catch (NacosException e) {
            e.printStackTrace();
        }

        return new NacosServer(instance);
    }
}
